<script lang="ts" setup>
import { onMounted, onUnmounted, ref, watch } from 'vue';

import {
  Button,
  Pagination,
  Popover,
  RadioButton,
  RadioGroup,
  Table,
} from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';

import CheckInvoice from './components/CheckInvoice.vue';
import IssueInvoice from './components/IssueInvoice.vue';
import RejectInvoice from './components/RejectInvoice.vue';

// 引入 columns 数组
import columns from './columns';

// 引入 ListItem 类型
import type { ListItem } from './columns';

import dayjs from 'dayjs';

import { getInvoiceCount, getInvoiceList } from '#/api';

const [QueryForm, formApi] = useVbenForm({
  // 默认展开
  collapsed: false,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
    // labelClass: 'justify-start', // 居左显示
  },
  // 提交函数
  handleSubmit: onSubmit,
  handleReset: onReset,
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入订单号',
        allowClear: true,
      },
      fieldName: 'orderNo',
      label: '订单号',
    },
    {
      component: 'RangePicker',
      componentProps: {
        disabledDate: (current: number) => {
          if (!current) return false;
          return current > new Date().setHours(23, 59, 59, 999);
        },
      },
      fieldName: 'startDatePicker',
      label: '申请时间',
    },
  ],
  // 是否可展开
  showCollapseButton: false,
  submitButtonOptions: {
    content: '查询',
  },
  wrapperClass: 'grid-cols-1 md:grid-cols-3',
});

// 分页器
const pagination = ref({
  pageSize: 20,
  pageNo: 1,
});
const total = ref(0);

// 表单数据是否加载中
const loading = ref<boolean>(true);

// 查询表单数据
const formData = ref<Record<string, any>>({
  startDatePicker: [],
  orderNo: '',
});
// 开票类型或者状态
const filterType = ref<string>('');
// 使用导入的 ListItem 类型
const list = ref<ListItem[]>([]);

// 查询接口
const getList = async () => {
  try {
    const { data } = await getInvoiceList({
      ...pagination.value,
      orderNo: formData.value?.orderNo || '',
      startTime: formData.value?.startDatePicker?.length
        ? `${dayjs(formData.value?.startDatePicker[0]).format(
            'YYYY-MM-DD',
          )} 00:00:00`
        : '',
      endTime: formData.value?.startDatePicker?.length
        ? `${dayjs(formData.value?.startDatePicker[1]).format(
            'YYYY-MM-DD',
          )} 23:59:59`
        : '',
      status: filterType.value === '' ? null : filterType.value,
    });
    // 这里是查询接口的实现
    list.value = data?.records || [];
    total.value = data.total || 0;
    loading.value = false;
  } catch (error) {
    loading.value = false;
    console.error('获取财务列表失败：', error);
  }
};

// 显示开票弹窗
const showIssueInvoice = ref<boolean>(false);
// 查看开票弹窗
const showCheckInvoice = ref<boolean>(false);
// 驳回弹窗
const showReject = ref<boolean>(false);
// 选中的行数据
const itemData = ref<ListItem>();
// 去开发票
const handleInvoice = (record: ListItem) => {
  itemData.value = record;
  showIssueInvoice.value = true;
};

// 查看发票
const seeInvoice = (record: ListItem) => {
  showCheckInvoice.value = true;
  itemData.value = record;
};

// 驳回
const handleReject = (record: ListItem) => {
  showReject.value = true;
  itemData.value = record;
};

// 数量统计
const totalObj = ref();
// 获取数量统计接口
const getCountTotal = async () => {
  try {
    const { data } = await getInvoiceCount({
      orderNo: formData.value?.orderNo || '',
      startTime: formData.value?.startDatePicker?.length
        ? `${dayjs(formData.value?.startDatePicker[0]).format(
            'YYYY-MM-DD',
          )} 00:00:00`
        : '',
      endTime: formData.value?.startDatePicker?.length
        ? `${dayjs(formData.value?.startDatePicker[1]).format(
            'YYYY-MM-DD',
          )} 23:59:59`
        : '',
    });
    totalObj.value = data || {};
  } catch (error) {
    console.error('获取数量统计失败：', error);
  }
};

// 分页改变事件
const onPageChange = async (page: number, pageSize: number) => {
  pagination.value.pageNo = page || 1;
  pagination.value.pageSize = pageSize || 10;
  loading.value = true;
  await getList();
};

// 查询事件
async function onSubmit(values: Record<string, any>) {
  formData.value = values;
  pagination.value.pageNo = 1;
  loading.value = true;
  total.value = 0;
  await getList();
  await getCountTotal();
}

// 重置事件
async function onReset() {
  pagination.value.pageNo = 1;
  loading.value = true;
  total.value = 0;
  await formApi.resetForm();
  await formApi.submitForm();
  await getCountTotal();
}

// 状态切换
const handleRadio = async () => {
  pagination.value.pageNo = 1;
  loading.value = true;
  total.value = 0;
  await getList();
  await getCountTotal();
};

const scrollY = ref<number>(500);
// 定义获取高度的函数
const getScrollY = () => {
  const height = window.innerHeight;
  const main = document.querySelector('#main') as HTMLElement;
  if (height < 600) {
    scrollY.value = 300;
  } else if (main) {
    const top = main.getBoundingClientRect().top;
    scrollY.value = height - top - 210;
  }
};

const init = async () => {
  await getList();
  await getCountTotal();
};
// 初始化
onMounted(() => {
  init();
  getScrollY();
  // 监听窗口大小变化
  window.addEventListener('resize', getScrollY);
});
// 组件卸载时移除监听
onUnmounted(() => {
  window.removeEventListener('resize', getScrollY);
});
// 监听 DOM 变化，确保 main 元素加载完成后更新高度
watch(
  () => document.querySelector('#main'),
  (newValue) => {
    if (newValue) {
      getScrollY();
    }
  },
  { immediate: true },
);

const status = {
  0: '待开发票',
  1: '已开票',
  2: '已拒绝',
  3: '取消申请',
};
</script>

<template>
  <div class="absolute bottom-0 right-0 h-[100%] w-[100%] overflow-hidden">
    <div class="flex h-[100%] w-[100%] flex-col overflow-auto p-5 pt-4">
      <div class="mb-4 text-xl font-bold">发票管理</div>
      <div class="card-box w-full pr-5 pt-6">
        <QueryForm />
      </div>
      <div id="main" class="card-box relative mt-4 w-full p-4">
        <RadioGroup
          v-model:value="filterType"
          class="mb-3"
          @change="handleRadio"
        >
          <RadioButton class="h-auto py-1" value="">
            全部({{ totalObj?.allNum || 0 }})
          </RadioButton>
          <RadioButton :value="0" class="h-auto py-1">
            待开票({{ totalObj?.waitReviewNum || 0 }})
          </RadioButton>
          <RadioButton :value="1" class="h-auto py-1">
            已开票({{ totalObj?.successNum || 0 }})
          </RadioButton>
        </RadioGroup>
        <Table
          :columns="columns"
          :data-source="list"
          :loading="loading"
          :pagination="false"
          :scroll="{ x: 2200, y: scrollY }"
          bordered
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <p>
                {{ status[record.status as 0 | 1 | 2 | 3] }}
              </p>
            </template>
            <template v-if="column.key === 'invoiceType'">
              <p>
                {{ record.invoiceType === 1 ? '普通发票' : '增值税专用发票' }}
              </p>
            </template>
            <template v-if="column.key === 'handle'">
              <div class="flex items-center justify-center">
                <Button
                  v-if="record.status === 0"
                  class="h-auto px-1 py-0"
                  type="link"
                  @click="handleInvoice(record as ListItem)"
                >
                  去开票
                </Button>
                <Button
                  v-if="record.status === 0"
                  class="h-auto px-1 py-0"
                  type="link"
                  @click="handleReject(record as ListItem)"
                >
                  驳回
                </Button>
                <Popover
                  v-else-if="record.status === 2"
                  placement="right"
                  title="驳回理由"
                >
                  <template #content>
                    <p>{{ record.refuseReason || '-' }}</p>
                  </template>
                  <Button class="h-auto p-0" type="link"> 查看理由 </Button>
                </Popover>
                <Button
                  v-else-if="record.status === 1"
                  class="h-auto px-1 py-0"
                  type="link"
                  @click="seeInvoice(record as ListItem)"
                >
                  查看发票
                </Button>
              </div>
            </template>
          </template>
        </Table>
        <div v-if="total > 0" class="flex justify-end pt-4">
          <Pagination
            v-model:current="pagination.pageNo"
            v-model:page-size="pagination.pageSize"
            :total="total"
            @change="onPageChange"
          />
        </div>
      </div>
    </div>
    <IssueInvoice
      v-model:show="showIssueInvoice"
      :data="itemData"
      @init-list="init"
    />
    <CheckInvoice v-model:show="showCheckInvoice" :data="itemData" />
    <RejectInvoice
      v-model:show="showReject"
      :data="itemData"
      @init-list="init"
    />
  </div>
</template>
